const httpResult = require("../lib/httpResult");
const _ = require("lodash");
let router = require('koa-router')();
let moment = require('moment');
const MyEmitter = require('../lib/MyEmitter');
const utils = require('../lib/utils');

let match = new MyEmitter(10, matchReport, async (result) => {console.log(result)});
match.name = 'report_match_thread';
match.startup();

let moMatch = new MyEmitter(10, matchMo, async (result) => {console.log(result)});
moMatch.name = 'mo_match_thread';
moMatch.startup();

/**
 * hexingtx sms channel api，accept report
 */
router.post('/report', httpResult.respRaw(async (ctx) => {
  let data = ctx.request.body;
  log.info('get report from channel, length : ', data.length, " - ", JSON.stringify(data));
  let reports = await models.mtReport.create(data);
  match.addTask(reports);
  return {
    code : '00000'
  }
}));

/**
 * hexingtx sms channel api，accept deliver message
 */
router.post('/mo', httpResult.respRaw(async (ctx) => {
  let data = ctx.request.body;
  log.info('get mo from channel', data);
  let mo = await models.moMsg.create(data);
  moMatch.addTask(mo);
  return {
    code : '00000'
  }
}));

async function matchReport(r) {
  let cReports = [];
  let q = {mobile: r.phone, mt_msg_id: r.uid,};
  let update = {
    report_status: r.status,
    report_desc: r.desc,
    report_time: new Date()
  }
  let mt = await models.mtMsg.findOneAndUpdate(q, update).lean();

  if (mt) {
    cReports.push({
      msg_id: mt.mt_msg_id,
      mobile: r.phone,
      status: r.status,
      desc : r.desc,
      report_date: r.report_time,
      send_date: moment(mt.send_time).format('YYYY-MM-DD HH:mm:ss'),
      pieces: mt.charge_count,
      ext: mt.ext,
      ticket: mt.request_id,
      ref: mt.ref,
      cus_id: mt.account,
      iso_code : utils.getIsoCodeByNumber(r.phone)
    })

    mt.report_status = update.report_status;
    mt.report_desc = update.report_desc;
    mt.report_time = update.report_time;

    try{
      let r1 = await models.mtMsgHistory.create(mt);
      let r2 = await models.mtMsg.deleteOne({_id : mt._id});
    }catch(err){
      log.error('删除下发记录异常：', err)
    }
    
    
    let saveResults = await models.customerReport.create(cReports);
    log.info('save customer_report', JSON.stringify(saveResults))
  }
  
}

async function matchMo(m) {
  let cMo = [];
  // let mt = await models.mtMsg.findOne({mobile: m.phone})
  // if (mt) {
    cMo.push({
      mobile: m.phone,
      mo_date: m.deliver_time,
      content: m.msg,
      ext: m.extend,
      cus_id: m.appkey
    })
  // }
  await models.customerMo.create(cMo);
}

module.exports = router;
